package project.fileAccess;
import project.*;
import java.util.ArrayList;
import java.io.*;
import java.sql.*;

public class ReadLocations {
    public ArrayList getDbList(){
        DatabaseInfo dbLocal = null;
        ArrayList<DatabaseInfo> dbList = new ArrayList<DatabaseInfo>();
        try {
        FileInputStream fis = new FileInputStream("local.dat");
        ObjectInputStream ois = new ObjectInputStream(fis);
        dbLocal = (DatabaseInfo)ois.readObject();
        ois.close();
     } catch (IOException e){
        System.err.println(e.getMessage());
    } catch (ClassNotFoundException e){
        System.err.println(e.getMessage());
    }
        try {
         FileInputStream fis = new FileInputStream("locations.dat");
        ObjectInputStream ois = new ObjectInputStream(fis);
    while(true){
        try{
           DatabaseInfo dbTemp = (DatabaseInfo)ois.readObject();
           if (!(dbTemp.getHostName().equals(dbLocal.getHostName())) || !(dbTemp.getDatabaseName().equals(dbLocal.getDatabaseName()))
                   || !(dbTemp.getUserName().equals(dbLocal.getUserName())) ){
    dbList.add(dbTemp);
   // System.out.println(dbTemp.getDatabaseName());
           }

		} catch (EOFException e){
            ois.close();
            break;
        }
    }
        } catch (IOException e) {
            System.err.println("File Not Found");
        } catch (ClassNotFoundException e){
            System.err.println("Class Not Found");
        }

        //
        try {
           Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (Exception e) {
            System.err.println("Error loading Driver");
			}
        for (int i=0;i<dbList.size();i++){
        try{

            Connection conn =DriverManager.getConnection("jdbc:mysql://" + dbList.get(i).getHostName()+":"+dbList.get(i).getPortNo()+"/"+dbList.get(i).getDatabaseName(),
		dbList.get(i).getUserName(),dbList.get(i).getPassword());

            
            conn.close();
        }catch (SQLException e) {
		System.err.println(e.getMessage());
        }
        }
        return dbList;
    }
}
